import os

from bson import ObjectId
from flask import Blueprint, request, send_file, jsonify
from setting import COVER_PATH, MUSIC_PATH, MONGODB, RET

devices = Blueprint("devices", __name__)


@devices.route("/bind_toy", methods=["POST"])
def bind_toy():

	# 获取玩具的绑定信息
	toy_info = request.form.to_dict()
	# 构建玩具的数据结构
	toy_info["avatar"] = "toy.jpg"
	user_id = toy_info.pop("user_id")
	toy_info["bind_user"] = user_id
	toy_info["friend_list"] = []

	# 构建玩具的好友信息
	# 1.将App用户信息 加入到 toy 的好友列表中(通讯录)
	user_info = MONGODB.users.find_one({"_id": ObjectId(user_id)})
	# 2.Toy没有被创建，所以没有Toy的_id 不能写入到 User_list 中
	chat = MONGODB.chats.insert_one({"user_list": [], "chat_list": []})
	# 3.构建玩具的好友信息 - app 用户
	friend_info = {
		"friend_id": user_id,
		"friend_nick": user_info.get("nickname"),
		"friend_remark": toy_info.pop("remark"),
		"friend_avatar": user_info.get("avatar"),
		"friend_chat": str(chat.inserted_id),
		"friend_type": "app"
	}
	toy_info["friend_list"].append(friend_info)

	# 创建玩具
	toy = MONGODB.toys.insert_one(toy_info)
	# 获取玩具的ID
	toy_id = str(toy.inserted_id)
	user_list = [toy_id, user_id]  # 创建聊天专属用户列表
	MONGODB.chats.update_one({"_id": chat.inserted_id}, {"$set": {"user_list": user_list}})

	# 好友关系 一般 ：一个人无法决定两人的关系 双方的
	user_add_toy = {
		"friend_id": toy_id,
		"friend_nick": toy_info.get("baby_name"),
		"friend_remark": toy_info.get("toy_name"),
		"friend_avatar": toy_info.get("avatar"),
		"friend_chat": str(chat.inserted_id),
		"friend_type": "toy"
	}

	# 为App用添加bind_toys的toy._id
	user_info["bind_toys"].append(toy_id)
	# 为App用户添加friend_list 的 toy
	user_info["friend_list"].append(user_add_toy)
	MONGODB.users.update_one({"_id": user_info.get("_id")}, {"$set": user_info})

	"""
	填写绑定信息 发送给 后台 
	后台将绑定信息 写入Toy表
	{
		"_id" : ObjectId("5ca17f85ea512d215cd9b079"), // 自动生成ID
		"toy_name" : "小粪球儿", // 玩具的昵称
		"baby_name" : "圆圆", // 玩具主人的昵称
		"device_key" : "afc59916257ae8a2b6ccdfb9fd273373", // 玩具的设备编号
		"avatar" : "toy.jpg", // 玩具的头像固定值 "toy.jpg"
		"bind_user" : "5c9d8da3ea512d2048826260", // 玩具的绑定用户
		"friend_list" : [ // 玩具通讯录信息 
			{ // 与Users数据表 friend_list 结构相同
				"friend_id" : "5c9d8da3ea512d2048826260",
				"friend_nick" : "DragonFire",
				"friend_remark" : "爸爸",
				"friend_avatar" : "baba.jpg",
				"friend_chat" : "5ca17f85ea512d215cd9b078",
				"friend_type" : "app"
			},
			{
				"friend_id" : "5ca17c7aea512d26281bcb8d",
				"friend_nick" : "臭屎蛋儿",
				"friend_remark" : "蛋蛋的忧伤",
				"friend_avatar" : "toy.jpg",
				"friend_chat" : "5ca5e789ea512d2e544da015",
				"friend_type" : "toy"
			}
		]
	}
	"""

	RET["CODE"] = 0
	RET["MSG"] = "绑定完成"
	RET["DATA"] = {}

	return jsonify(RET)


@devices.route("/scan_qr", methods=["POST"])
def scan_qr():
	device_info = request.form.to_dict()
	device = MONGODB.devices.find_one(device_info)
	if device:  # 蜜汁逻辑-是否已经绑定
		RET["CODE"] = 0
		RET["MSG"] = "二维码扫描成功"
		RET["DATA"] = device_info
	else:
		RET["CODE"] = 1
		RET["MSG"] = "请扫描玩具二维码"
		RET["DATA"] = {}

	return jsonify(RET)


@devices.route("/open_toy", methods=["POST"])
def open_toy():
	device_info = request.form.to_dict()
	device = MONGODB.devices.find_one(device_info)
	if device:  # 证明 设备存在
		ret = {
			"code": 1,
			"music": "Nobind.mp3"
		}
		toy = MONGODB.toys.find_one(device_info)
		if toy:
			ret = {
				"code": 0,
				"music": "Success.mp3",
				"toy_id": str(toy.get("_id")),
				"name": toy.get("toy_name")
			}

	else:  # 设备不存在
		ret = {
			"code": 2,
			"music": "Nolic.mp3"
		}

	return jsonify(ret)


@devices.route("/toy_list", methods=["POST"])
def toy_list():
	user_id = request.form.get("_id")
	#  第一种方式
	# 1.查询当前用户的信息
	# 2.获取用户绑定的玩具 bind_toys
	# 3.根据bind_toys去查询玩具
	# 4.做一个列表然后返回

	# 第二种方式
	# 根据Toys 表里的 bind_user
	toy_l = list(MONGODB.toys.find({"bind_user":user_id}))
	for index,item in enumerate(toy_l):
		toy_l[index]["_id"] = str(item.get("_id"))

	"""
	{
	"code":0,
	"msg":"获取Toy列表",
	"data":
	[
		{
            "_id" : "5bcdaaa6268d794ec8af3fa2",
            "device_key" : "bc557bcc9570069a494a64eb38698d35",
            "bind_user" : "5bcda858268d796fc8d3e3de",
            "toy_name" : "蛋蛋",
            "avatar" : "toy.jpg",
            "baby_name" : "臭屎蛋儿",
            "gender" : "1",
            "friend_list" : [
                {
                    "friend_nickname" : "淫王",
                    "friend_avatar" : "girl.jpg",
                    "friend_remark" : "爸爸",
                    "friend_chat" : "5bcdaaa6268d794ec8af3fa1"
                }
            ]
        }
    ]
	"""

	RET["CODE"] = 0
	RET["MSG"] = "获取Toy列表"
	RET["DATA"] = toy_l

	return jsonify(RET)